<template>
	<div>
		<el-card shadow="always" class="search">
			<el-form
				:inline="true"
				:model="formInline"
				class="demo-form-inline"
			>
				<el-form-item label="请输入内容">
					<el-input
						v-model="formInline.user"
						placeholder="根据用户名搜索"
						clearable
						@blur="getInputVal"
					></el-input>
				</el-form-item>
				<el-form-item label="创建时间" class="creat-time">
					<el-date-picker
						v-model="formInline.date"
						type="daterange"
						align="right"
						unlink-panels
						range-separator="至"
						start-placeholder="开始日期"
						end-placeholder="结束日期"
						:picker-options="pickerOptions"
						@change="changedate(formInline.date)"
						value-format="yyyy-MM-dd"
					>
					</el-date-picker>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="onSubmit">查询</el-button>
				</el-form-item>
			</el-form>
		</el-card>

		<div class="add">
			<el-button
				type="primary"
				icon="el-icon-circle-plus-outline"
				size="medium"
				@click="addUser"
				>添加</el-button
			>
			<el-button
				type="danger"
				icon="el-icon-delete"
				size="medium"
				:disabled="selectedRows.length === 0"
				@click="handelDeleteMore"
				>删除</el-button
			>
			<el-button
				icon="el-icon-refresh-right"
				size="medium"
				@click="handelRefresh"
				:loading="loading"
				>刷新列表</el-button
			>
		</div>
		<div class="tables">
			<el-table
				:data="tableData"
				stripe=""
				empty-text="暂未添加任何账号"
				@selection-change="handleSelectedRows"
				v-top
				v-width
				v-loading="tableLoading"
				element-loading-text="拼命加载中"
				style="width: 100%"
			>
				<el-table-column
					type="selection"
					width="50"
					align="center"
					fixed="left"
				></el-table-column>
				<el-table-column
					label="用户名称"
					width="150"
					prop="nickname"
					sortable=""
					:formatter="notEmpty"
				>
				</el-table-column>
				<el-table-column
					label="用户名"
					min-width="150"
					prop="username"
					sortable=""
					:formatter="notEmpty"
				></el-table-column>
				<el-table-column
					label="手机号"
					width="150px"
					align="center"
					prop="mobile"
					sortable=""
					:formatter="notEmpty"
				></el-table-column>
				<el-table-column
					label="邮箱号"
					width="150px"
					align="center"
					prop="email"
					sortable=""
					:formatter="notEmpty"
				></el-table-column>
				<el-table-column
					label="QQ号"
					width="150px"
					align="center"
					prop="qq"
					sortable=""
					:formatter="notEmpty"
				></el-table-column>
				<el-table-column
					label="性别"
					width="100px"
					align="center"
					prop="sex"
					sortable=""
					:formatter="formatSex"
				></el-table-column>
				<el-table-column
					label="是否启用"
					width="100"
					align="center"
					prop="status"
					sortable=""
					:formatter="notEmpty"
				>
					<template slot-scope="scope">
						<el-switch
							v-model="scope.row.status"
							:active-value="1"
							:inactive-value="0"
							@change="
								(data) => handleChangeStatus(data, scope.row)
							"
						></el-switch>
					</template>
				</el-table-column>
				<el-table-column
					label="最后一次登录时间"
					width="200"
					prop="last_login_time"
					align="center"
					sortable=""
					:formatter="notEmpty"
				></el-table-column>
				<el-table-column
					label="创建时间"
					width="200"
					prop="create_time"
					align="center"
					sortable=""
					:formatter="notEmpty"
				></el-table-column>
				<el-table-column
					label="更新时间"
					width="200"
					prop="update_time"
					align="center"
					sortable=""
					:formatter="notEmpty"
				></el-table-column>
				<el-table-column
					label="操作"
					width="200"
					fixed="right"
					align="center"
					:formatter="notEmpty"
				>
					<template slot-scope="scope">
						<el-button-group>
							<el-button
								size="mini"
								round
								type="primary"
								@click="handleEdit(scope.row)"
								>修改</el-button
							>
							<el-button
								size="mini"
								round
								type="danger"
								@click="handleDelete(scope.row.id)"
								>删除</el-button
							>
						</el-button-group>
					</template>
				</el-table-column>
			</el-table>
		</div>
		<div class="pagenation">
			<!-- <Pagination 
			:total="total"
			:pageSize="pageSize"
			>
			</Pagination> -->
			<el-pagination
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
				:current-page="queryInfo.pageNum"
				:page-sizes="[5, 10, 15, 20]"
				:page-size="queryInfo.pageSize"
				layout="total, sizes, prev, pager, next, jumper"
				background
				v-show="total > 10"
				:total="total"
			>
			</el-pagination>
		</div>
		<el-dialog
			:title="user.id ? '修改用户' : '添加用户'"
			:visible.sync="dialogVisible"
			width="680px"
		>
			<el-form
				:model="addFormInline"
				label-position="left"
				label-width="80px"
				:rules="rules"
				ref="form"
				@submit.native.prevent
			>
				<el-row :gutter="20">
					<el-col :span="12">
						<el-form-item label="称呼" prop="nickname">
							<el-input
								v-model="addFormInline.nickname"
								placeholder="请输入称呼"
							></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="手机号" prop="mobile">
							<el-input
								v-model="addFormInline.mobile"
								placeholder="请输入手机号"
							></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="QQ号" prop="qq">
							<el-input
								v-model="addFormInline.qq"
								placeholder="请输入QQ号"
							></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="用户名" prop="username">
							<el-input
								v-model="addFormInline.username"
								placeholder="请输入用户名"
							></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="性别" prop="sex">
							<el-radio-group v-model="addFormInline.sex">
								<el-radio :label="1">男</el-radio>
								<el-radio :label="0">女</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="邮箱号" prop="email">
							<el-input
								v-model="addFormInline.email"
								placeholder="请输入邮箱号"
							></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="密码" prop="password">
							<el-input
								v-model="addFormInline.password"
								placeholder="请输入密码"
							></el-input>
						</el-form-item>
					</el-col>

					<el-col :span="12">
						<el-form-item label="角色" prop="role_id">
							<el-select
								v-model="addFormInline.role_id"
								placeholder="请分配角色"
							>
								<el-option
									v-for="item in rule"
									:label="item.name"
									:value="item.id"
									:key="item.id"
								></el-option>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitAdd">确 定</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
import { cloneDeep } from 'lodash';
import http from '@/utils/http';
import qs from 'qs';
// import Pagination from '../../components/pagination/Pagination.vue'
import Vue from 'vue';
/* Vue.filter(formartSex, (value)=>{
  if( value == 1) return "男";
  if( value == 2) return "女";
}) */

/**
 * * 添加自定义属性获取当前页面高度和宽度
 */
Vue.directive('top', {
	inserted(el) {
		console.log('当前高度当前高度当前高度');
		console.log(el);
		window.onscroll = () => {
			if (document.documentElement.scrollTop > 30) {
				console.log('滚动');
			} else {
				console.log('噜啦噜啦嘞绿绿绿');
			}
		};
	},
	unbind() {
		console.log('当前高度');
		window.onscroll = null;
	},
});
Vue.directive('width', {
	inserted(el) {
		console.log('当前宽度当前宽度当前宽度当前宽度');
		console.log(el);
	},
	unbind() {
		console.log('当前宽度');
	},
});
export default {
	/* components: {
		Pagination,
	}, */
	data() {
		return {
			disabled: true,
			dialogVisible: false,
			ids: [],
			// 角色列表
			rule: [],
			// 加载中状态
			loading: false,
			tableLoading: true,
			// 搜索数据
			formInline: {
				user: '',
				date: [],
			},
			user: {},
			// 初始化表单数据
			addFormInline: {
				nickname: '',
				mobile: '',
				qq: '',
				username: '',
				sex: 1,
				email: '',
				password: '',
				role_id: '',
			},
			// 表单校验规则
			rules: {
				nickname: [
					{
						required: true,
						message: '称呼不能为空',
						trigger: 'blur',
					},
					{
						min: 3,
						max: 11,
						message: '长度在 3 到 11 个字符',
						trigger: 'blur',
					},
				],
				mobile: [
					{
						required: true,
						message: '电话不能为空',
						trigger: 'blur',
					},
					{
						min: 3,
						max: 11,
						message: '长度在 3 到 11 个字符',
						trigger: 'blur',
					},
				],
				qq: [
					{ required: true, message: 'qq不能为空', trigger: 'blur' },
					{
						min: 3,
						max: 11,
						message: '长度在 3 到 11 个字符',
						trigger: 'blur',
					},
				],
				username: [
					{
						required: true,
						message: '用户名不能为空',
						trigger: 'blur',
					},
					{
						min: 3,
						max: 11,
						message: '长度在 3 到 11 个字符',
						trigger: 'blur',
					},
				],
				sex: [
					{
						required: true,
						message: '年龄不能为空',
						trigger: 'blur',
					},
				],
				email: [
					{
						required: false,
						message: '称呼不能为空',
						trigger: 'blur',
					},
					{
						min: 3,
						max: 11,
						message: '长度在 3 到 11 个字符',
						trigger: 'blur',
					},
				],
				password: [
					{
						required: true,
						message: '密码不能为空',
						trigger: 'blur',
					},
					{
						min: 3,
						max: 11,
						message: '长度在 3 到 11 个字符',
						trigger: 'blur',
					},
				],
				role_id: [
					{
						required: true,
						message: '角色不能为空',
						trigger: 'blur',
					},
				],
			},
			// 日期选择器
			pickerOptions: {
				shortcuts: [
					{
						text: '最近一周',
						onClick(picker) {
							const end = new Date();
							const start = new Date();
							start.setTime(
								start.getTime() - 3600 * 1000 * 24 * 7
							);
							picker.$emit('pick', [start, end]);
						},
					},
					{
						text: '最近一个月',
						onClick(picker) {
							const end = new Date();
							const start = new Date();
							start.setTime(
								start.getTime() - 3600 * 1000 * 24 * 30
							);
							picker.$emit('pick', [start, end]);
						},
					},
					{
						text: '最近三个月',
						onClick(picker) {
							const end = new Date();
							const start = new Date();
							start.setTime(
								start.getTime() - 3600 * 1000 * 24 * 90
							);
							picker.$emit('pick', [start, end]);
						},
					},
				],
			},
			// 表格数据
			tableData: [],
			// 表格最大高度
			// maxHeight: document.documentElement.clientHeight - 300,
			// 复选框选中的数据
			selectedRows: [],
			// dialog 标题
			dialogFormTitle: '',
			// 分页组件
			total: 0, // 总条数
			queryInfo: {
				pageSize: 10,
				pageNum: 1,
			},
		};
	},
	created() {
		/**
		 * todo: 加入table 加载loading
		 * todo: 性别改写过滤器形式
		 * todo: 禁用/启用
		 * todo: 分页功能实现
		 * todo: 自定义指令
		 */
		this.getList();
		this.getUserRules();
	},
	computed: {
		keyword() {
			return this.formInline.user;
		},
	},
	watch: {
		keyword(keyword) {
			if (!keyword) this.getList();
		},
	},

	methods: {
		// 时间选择
		changedate(data) {
			// console.log(data[1])
			// console.log(data[0])
		},
		// 查询
		onSubmit() {
			this.getList();
		},
		getInputVal() {
			console.log(this.formInline.user);
		},
		/**
		 * 获取列表数据
		 * todo: 1> 加入loading, 2> loading状态判断, 3> 初始状态加入计算属性, 4> 提交
		 */
		async getList() {
			const limit = this.queryInfo.pageSize,
				page = this.queryInfo.pageNum,
				keyword = this.formInline.user,
				startTime = this.formInline.date[0],
				endTime = this.formInline.date[1];
			const form = { limit, page, keyword, startTime, endTime };
			console.log(form);
			this.tableLoading = true;
			const { data: res } = await http.get('admin_management/list', {
				params: form,
			});
			this.tableLoading = false;
			console.log(res.data);
			this.tableData = res.data.data;
			this.total = res.data.total;
		},
		// 分页器实现
		handleSizeChange(val) {
			//  console.log(`每页 ${val} 条`);
			this.queryInfo.pageSize = val;
			this.getList();
		},
		handleCurrentChange(val) {
			//    console.log(`当前页: ${val}`);
			this.queryInfo.pageNum = val;
			this.getList();
		},
		// 获取角色列表
		async getUserRules() {
			const { data: res } = await http.get('/admin_management/getRoles');
			this.rule = res.data;
		},
		//刷新
		handelRefresh() {
			this.loading = true;
			this.tableLoading = true;
			this.getList().then(() => {
				this.$message({
					message: '刷新成功',
					type: 'success',
				});
				this.loading = false;
				this.tableLoading = false;
			});
		},
		// 添加
		addUser() {
			// this.user = {}
			// return false;
			console.log('清空表单');
			this.$nextTick(() => {
				this.$refs.form.resetFields();
				this.$refs.form.clearValidate();
			});
			this.dialogVisible = true;
			return false;
		},
		// 新建或修改用户
		submitAdd() {
			this.$refs.form.validate(async (vaild) => {
				const addFormInline = cloneDeep(this.addFormInline);
				console.log(addFormInline);
				if (!vaild) {
					return false;
				}
				// 更新信息/新建信息
				if (this.user.id) {
					console.log('更新');
					console.log(addFormInline);
					console.log(addFormInline.nickname);
					const updateUserInfo = {
						nickname: addFormInline.nickname,
						mobile: addFormInline.mobile,
						qq: addFormInline.qq,
						username: addFormInline.username,
						sex: addFormInline.sex,
						email: addFormInline.email,
						password: addFormInline.password,
						role_id: addFormInline.role_id,
					};
					http.post('/admin_management/update', updateUserInfo)
						.then((res) => {
							if (res.data.code == 200) {
								this.$message.success(res.data.msg);
								// 清空表单
								this.$refs.form.resetFields();
							} else {
								this.$message.warning(res.data.msg);
							}
							this.getList();
						})
						.catch((err) => {
							this.$message.error('操作失败');
						});
				} else {
					//新建
					http.post('/admin_management/create', addFormInline)
						.then((res) => {
							if (res.data.code == 200) {
								this.$message.success(res.data.msg);
								// 重新获取列表
								this.getList();
								// 清空表单
								this.$refs.form.resetFields();
							} else {
								this.$message.warning(res.data.msg);
							}
						})
						.catch((err) => {
							this.$message.error('操作失败');
						});
				}
				this.dialogVisible = false;
			});
		},
		// 单个删除
		async handleDelete(id) {
			const confirmResult = await this.$confirm(
				'是否删除当前用户?',
				'提示',
				{
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning',
				}
			).catch((error) => error);
			if (confirmResult != 'confirm') {
				console.log(confirmResult);
				return this.$message.info('取消删除');
			}
			const { data: res } = await http.post('/admin_management/remove', {
				id: id,
			});
			if (res.code == 200) {
				this.$message.success(res.msg);
				this.getList();
			} else {
				this.$message.warning(res.msg);
			}
		},
		/**
		 * 当选中行
		 * @param {array} rows 选中行数据
		 * 列表选中状态数据
		 */
		handleSelectedRows(selection) {
			console.log(selection);
			var selectedRows = selection.map((item) => item.id);
			this.selectedRows = selectedRows.join(',');
			console.log('this.selectedRows', this.selectedRows);
		},
		// 批量删除
		handelDeleteMore() {
			this.$confirm('确定删除多个用户吗?', '提示')
				.then(async () => {
					const { data: res } = await http.post('/admin_management/remove',{ id: this.selectedRows });
					if (res.code === 200) {
						this.$message.success(res.msg);
						this.getList();
					} else {
						this.$message.error(res.msg);
					}
				})
				.catch(() => {
					this.$message.info('取消删除');
				});
		},
		/**
		 * 格式化性别
		 */
		formatSex(row, col, value, index) {
			if (value == 1) return '男';
			if (value == 0) return '女';
		},
		/**
		 *  修改
		 */
		handleEdit(user) {
			// console.log(user)
			// console.log(this.addFormInline)
			this.addFormInline = user;
			// console.log(this.addFormInline)
			this.user = cloneDeep(user);
			this.dialogVisible = true;
		},
		// 检查数据是否为空,如果空就返回 value
		notEmpty(row, col, value, index) {
			return value || '-';
		},
		// 启用状态改变
		async handleChangeStatus(data, scope) {
			const id = scope.id,
				  status = scope.status;
			const { data: res } = await http.post('/admin_management/update', {
				id,
				status,
				handle: 'change_status',
			});
			console.log(res);
			if (res.code == 200) {
				this.$message.success(res.msg);
			} else {
				this.$message.error(res.msg);
			}
			this.getList();
		},
	},
};
</script>

<style scoped lang='scss'>
/deep/ .el-card__body {
	padding: 20px 20px 0 20px !important;
	.creat-time {
		padding-left: 60px;
	}
}
.add {
	// background-color: #1aad19;
	margin-top: 20px;
}
.tables {
	background-color: #cee4ed;
	margin-top: 20px;
}
.pagenation {
	width: 100%;
	height: 50px;
}
</style>
